package cn.iocoder.yudao.module.game.service.otherGame;

import cn.iocoder.yudao.module.game.controller.admin.gameToken.vo.GameTokenSaveReqVO;
import cn.iocoder.yudao.module.game.dal.dataobject.gameToken.GameTokenDO;
import cn.iocoder.yudao.module.game.service.gameToken.GameTokenService;
import cn.iocoder.yudao.module.game.utils.AESEncrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import net.sf.json.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 游戏列表 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class TADAServiceImpl implements TADAService {


    // 测试
    private String agentId = "51GROUP_Seamless";
//    private String agentKey = "bbebedfb6c19db457202ff74640a67c24105ddfd";
//    private String apiUrl = "https://uat-wb-api.tadagaming.com/api1/";

    // 正式
    private String agentKey = "6f5f20831ae22df23dc1ec21980d1c34e9f9e78c";
    private String apiUrl = "https://wb-api-2.tadagaming.com/api1/";
    private String radomStr = "123456";

    @Resource
    private GameTokenService gameTokenService;

    @Override
    public JSONObject login(Map<String, Object> params) throws Exception {
        ZonedDateTime zonedDateTime = ZonedDateTime.now(java.time.ZoneId.of("America/Caracas"));
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyMMd");
        String now = zonedDateTime.format(formatter);; // 2019/01/01 => "19011"
        System.out.println("time:  " + now);
        System.out.println("agentId:  " + agentId);
        System.out.println("agentKey:  " + agentKey);
        String keyG = DigestUtils.md5Hex(now + agentId + agentKey);
        System.out.println("keyG:  " + keyG);

        String queryParams= "Token=" + params.get("token") +
                "&GameId=" + params.get("gameId") +
                "&Lang=pt-BR" +
                "&AgentId=" + agentId;
        System.out.println("queryParams:  " + queryParams);
        String key = radomStr + DigestUtils.md5Hex(queryParams + keyG) + radomStr;
        System.out.println("key:  " + key);

        String action = "singleWallet/LoginWithoutRedirect";

        CloseableHttpClient client = HttpClientBuilder.create().build();

        queryParams += "&HomeUrl=" + "http://tg.51win01.com/";
        queryParams += "&Key=" + key;

        System.out.println(apiUrl + action);

        HttpGet httpGet = new HttpGet(apiUrl + action + "?" + queryParams);
        HttpEntity httpEntity = null;
        String res = "{}";
        try {
            // Resolve response
            HttpResponse response = client.execute(httpGet);
            httpEntity = response.getEntity();
            res = EntityUtils.toString(httpEntity);
            System.out.println("POST:  " + res);
        } finally {
            EntityUtils.consume(httpEntity);
        }

        return JSONObject.fromObject(res);
    }

    @Override
    public String getToken(String userId) throws Exception {
        GameTokenDO gameTokenDO = gameTokenService.getToken(new LambdaQueryWrapper<GameTokenDO>()
                .eq(GameTokenDO::getMemberId, userId)
                .eq(GameTokenDO::getGameType, "TADA"));
        if (gameTokenDO != null) {
            return gameTokenDO.getToken();
        }

        System.out.println("getToken=========== ");
        String token = AESEncrypt.encrypt(agentId + agentKey + userId, agentId.substring(0, 16), agentKey.substring(0, 16));
        System.out.println("token: " + token);

        GameTokenSaveReqVO createReqVO = new GameTokenSaveReqVO();
        createReqVO.setMemberId(Long.valueOf(userId));
        createReqVO.setToken(token);
        createReqVO.setGameType("TADA");
        gameTokenService.createToken(createReqVO);

        return token;
    }

    @Override
    public GameTokenDO checkToken(String token) throws Exception {
        GameTokenDO gameTokenDO = gameTokenService.getToken(new LambdaQueryWrapper<GameTokenDO>()
                .eq(GameTokenDO::getToken, token)
                .eq(GameTokenDO::getGameType, "TADA"));
        return gameTokenDO;
    }
}